package service

import (
	"backend/app/dao"
	"backend/app/model"
	"backend/utils/format"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

var RoleService *roleService

func init() {
	RoleService = NewRoleService()
}

func NewRoleService() *roleService {
	return &roleService{}
}

type roleService struct {
}

func (svr *roleService) AddRole(p *model.UserAddRoleReqData, c *gin.Context) (data interface{}, err IServiceError) {
	roleName := p.RoleName
	if len(roleName) == 0 {
		err = NewServiceError(format.CodeRoleNameIsNil)
		return
	}
	isExist, dErr := dao.CheckRoleIsExist(roleName)
	if dErr != nil {
		zap.L().Error("AddRole CheckRoleIsExist is error", zap.Error(dErr))
		err = NewServiceError(format.CodeDatabaseErr)
		return
	}
	if isExist {
		err = NewServiceError(format.CodeRoleNameIsExist)
		return
	}
	newRole := &model.Role{
		RoleName: roleName,
	}
	if dErr := dao.SaveRole(newRole); dErr != nil {
		zap.L().Error("AddRole SaveRole is dErr,", zap.Error(dErr))
		err = NewServiceError(format.CodeDatabaseErr)
		return
	}
	return
}
